import random

import click
from faker import Faker
from models.books import BoardModel,BookModel
from exts import db
from models.user import PermissionEnum, PermissionModel, RoleModel, UserModel
from werkzeug.security import generate_password_hash

# 新建图书分类
def create_board():
    for i in ['计算机','军事','历史','文学','科幻','艺术','体育']:
        board = BoardModel(name=i)
        db.session.add(board)
    db.session.commit()
    click.echo("图书分类数据添加成功!")


# 新建图书
def create_book():
    fake = Faker(locale='zh_CN')
    boards = BoardModel.query.all()
    click.echo("开始生成虚拟数据")
    for x in range(98):
        title = fake.sentence()
        random_index = random.randint(0,6)
        board = boards[random_index]
        book = BookModel(name=title,board=board)
        db.session.add(book)
    db.session.commit()
    click.echo("虚拟数据生成成功")


def add_book_author_name():
    fake = Faker(locale='zh_CN')
    click.echo("开始生成虚拟数据")
    books = BookModel.query.all()
    for book in books:
        author_name = fake.name()
        book.author_name = author_name

    db.session.commit()
    click.echo("虚拟数据生成成功")

# 添加权限的命令
def create_permission():
    for permission_name in dir(PermissionEnum):
        if permission_name.startswith("__"):
            continue
        permission = PermissionModel(name=getattr(PermissionEnum,permission_name))
        db.session.add(permission)
    db.session.commit()
    click.echo("权限添加成功")

# 添加角色
def create_role():
    librarian = RoleModel(name='图书管理员',desc='管理图书馆的图书和图书类别')
    librarian.permissions =PermissionModel.query.\
        filter(PermissionModel.name.in_([PermissionEnum.BOOK,PermissionEnum.BOARD])).all()

    administrator = RoleModel(name="系统管理员",desc='拥有所有权限')
    administrator.permissions= PermissionModel.query.all()

    db.session.add_all([librarian,administrator])
    db.session.commit()
    click.echo("角色添加成功!")


def add_desc():
    fake = Faker("zh_CN")
    books = BookModel.query.all()
    click.echo("开始添加描述")
    for book in books:
        book.desc = fake.text(max_nb_chars=100)
        db.session.add(book)
    db.session.commit()
    click.echo("描述添加完成")


# 添加员工
def add_emp():
    user1 = UserModel(username="张三",email="25864405123@qq.com",password=generate_password_hash("123456"),
                      is_staff=True,role_id=1)
    user2 = UserModel(username="李四",email="45651233211@126.com",password=generate_password_hash("123456"),
                      is_staff=True,role_id=2)
    db.session.add_all([user1,user2])
    db.session.commit()
    click.echo("员工添加成功")


def add_user():
    user1 = UserModel(username="赵二麻子",password=generate_password_hash("123123"),email="zhihu@163.com")
    user2 = UserModel(username="shuiguo",password=generate_password_hash("123123"),email="124321543@qq.com")
    db.session.add_all([user1,user2])
    db.session.commit()
    click.echo("添加成功!")